package cn.fl.capital.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapFundVfDtlQueryCondition;
import cn.fl.capital.condition.CapFundVfLogQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.service.ICapFundVfDtlService;
import cn.fl.capital.vo.CapFundVfDtlVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 客户资金核销记录表 控制层
 */
@Controller
@RequestMapping("/capital/capFundVfDtl")
public class CapFundVfDtlController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(CapFundVfDtlController.class);

	/**
	 * 资金分解明细 服务层BEAN
	 */
	@Autowired
	private ICapFundVfDtlService capFundVfDtlService;

    /**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载CapFundVerification列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capFundVerification/capFundVerificationList");
		return mav;
	}
	
	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载CapFundVerification Add页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capFundVerification/capFundVerificationModify");
		//this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载CapFundVerification Modify页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capFundVerification/capFundVerificationModify");
		//this.prepare(request,mav);
		
		String id=request.getParameter("id");
		CapFundVfDtlVO capFundVerificationVO = this.capFundVfDtlService.selectById(Long.valueOf(id));
        mav.addObject("capFundVerificationVO", capFundVerificationVO);
		return mav;
	}
	
	//加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request,ModelAndView mav){
    	
    }

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initCapFundVerificationList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		
        //设置查询条件
		CapFundVfDtlQueryCondition qc = new CapFundVfDtlQueryCondition();
		
		String buOrgCd = request.getParameter("buOrgCd"); //事业部 代码
		String paySchNo = request.getParameter("paySchNo"); //支付表号
		String lsCntNo = request.getParameter("lsCntNo");//合同号
		String vfNo = request.getParameter("vfNo"); //分解单号
		String fundCd = request.getParameter("fundCd"); //资金编号
		String vfTmMin = request.getParameter("vfTmMin"); //分解时间
		String vfTmMax = request.getParameter("vfTmMax"); //分解时间
		
		if (StringUtils.isNotEmpty(buOrgCd)) {
               qc.setBuOrgCd(buOrgCd);
		}
		if (StringUtils.isNotEmpty(paySchNo)) {
            qc.setPaySchNo(paySchNo);
		}
		if (StringUtils.isNotBlank(lsCntNo)) {
			qc.setLsCntNo(lsCntNo);
		}
		if (StringUtils.isNotEmpty(vfNo)) {
            qc.setVfNo(vfNo);
		}
		if (StringUtils.isNotEmpty(fundCd)) {
            qc.setFundCd(fundCd);
		}
	    if (StringUtils.isNotBlank(vfTmMax)) {
	            qc.setVfTmMax(vfTmMax.trim());
	    }
	    if (StringUtils.isNotBlank(vfTmMin)) {
	            qc.setVfTmMin(vfTmMin.trim());
	    }
		
		
       qc.setVfTypCd(CapitalConstant.CODE_VF_TYP_CD_1);
       qc.setVfStsCd(CapitalConstant.CODE_CAP_FUND_STS_CD_2);
		
		page.setCondition(qc);

		BaseLogUtils.info(logger, "initCapFundVerificationList", "初始化CapFundVerification列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		Pager pager = this.capFundVfDtlService.searchListPage(page);
		List<CapFundVfDtlVO> list = (List<CapFundVfDtlVO>) pager.getResultList();
		ListPageVO<CapFundVfDtlVO> listPage = new ListPageVO<CapFundVfDtlVO>(list, pager.getTotalCount());
		return listPage;
	}
	
    /****************************
     * 导出资金分解支付表明细
     ****************************/
    @RequestMapping(value = "/exportDecomList.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO exportDecomList(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "exportDecomList", "批量导出资金分解单明细==");
        //设置查询条件
  		CapFundVfDtlQueryCondition qc = new CapFundVfDtlQueryCondition();
  		String buOrgCd = request.getParameter("buOrgCd"); //事业部 代码
		String paySchNo = request.getParameter("paySchNo"); //支付表号
		String lsCntNo = request.getParameter("lsCntNo");//合同号
		String vfNo = request.getParameter("vfNo"); //分解单号
		String fundCd = request.getParameter("fundCd"); //资金编号
		String vfTmMin = request.getParameter("vfTmMin"); //分解时间
		String vfTmMax = request.getParameter("vfTmMax"); //分解时间
		
		if (StringUtils.isNotEmpty(buOrgCd)) {
               qc.setBuOrgCd(buOrgCd);
		}
		if (StringUtils.isNotEmpty(paySchNo)) {
            qc.setPaySchNo(paySchNo);
		}
		if (StringUtils.isNotBlank(lsCntNo)) {
			qc.setLsCntNo(lsCntNo);
		}
		if (StringUtils.isNotEmpty(vfNo)) {
            qc.setVfNo(vfNo);
		}
		if (StringUtils.isNotEmpty(fundCd)) {
            qc.setFundCd(fundCd);
		}
		if (StringUtils.isNotBlank(vfTmMax)) {
	            qc.setVfTmMax(vfTmMax.trim());
	    }
	    if (StringUtils.isNotBlank(vfTmMin)) {
	            qc.setVfTmMin(vfTmMin.trim());
	    }
		
		
  		if (StringUtils.isNotEmpty(buOrgCd)) {
                 qc.setVfTypCd(CapitalConstant.CODE_VF_TYP_CD_1);
                 qc.setVfStsCd(CapitalConstant.CODE_CAP_FUND_STS_CD_2);
                 return this.capFundVfDtlService.exportDecomposeList(qc);
  		}else{
  			 DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_NO, "事业部类型不能为空");
  			 BaseLogUtils.info(logger, "exportDecomList", "查询capFundVfDtlService数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
  		}
    }
	

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeCapFundVerificationByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeCapFundVerificationByIds", "删除CapFundVerification数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
		
		try {
			boolean success = this.capFundVfDtlService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeCapFundVerificationByIds", "删除CapFundVerification数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeCapFundVerificationByIds", "删除CapFundVerification数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removeCapFundVerificationByIds", "删除CapFundVerification数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeCapFundVerificationByIds", "删除CapFundVerification数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getCapFundVerificationById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getCapFundVerificationById", "获取CapFundVerification数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			CapFundVfDtlVO vo = this.capFundVfDtlService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getCapFundVerificationById", "获取CapFundVerification数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getCapFundVerificationById", "获取CapFundVerification数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getCapFundVerificationById", "获取CapFundVerification数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getCapFundVerificationById", "获取CapFundVerification数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addCapFundVerification(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		CapFundVfDtlVO entity = null;//获取参数
		try {
			entity = this.getRequestParamForCapFundVerification(request);//获取参数
			Long id = this.capFundVfDtlService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "addCapFundVerification", "新增CapFundVerification数据成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "addCapFundVerification", "新增CapFundVerification数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addCapFundVerification", "新增CapFundVerification数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyCapFundVerification(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		CapFundVfDtlVO entity = null;
		try {
			entity = this.getRequestParamForCapFundVerification(request);
			if(entity.getId()==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifyCapFundVerification", "修改CapFundVerification信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}

			boolean success = this.capFundVfDtlService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyCapFundVerification", "修改CapFundVerification数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifyCapFundVerification", "修改CapFundVerification数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "modifyCapFundVerification", "修改CapFundVerification数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "modifyCapFundVerification", "修改CapFundVerification数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return 
	 */
	private CapFundVfDtlVO getRequestParamForCapFundVerification(HttpServletRequest request) throws BaseException{
		//获取参数
		String id = request.getParameter("id");//主键
		String fundId = request.getParameter("fundId");//资金ID
		String vfWayCd = request.getParameter("vfWayCd");//核销方式CAP0003：0—手动核销 1—自动核销
		String vfStsCd = request.getParameter("vfStsCd");//核销状态集合 CAP0004：0.未核销1.核销中2.已核销3.已作废4.冲红中5.已冲红6.已转出
		String paySchId = request.getParameter("paySchId");//支付表ID
		String paySchNo = request.getParameter("paySchNo");//支付表号
		String payDetailId = request.getParameter("payDetailId");//支付明细表ID
		String payPd = request.getParameter("payPd");//支付表期次
		String feeTypCd = request.getParameter("feeTypCd");//费用类型代码（PRJ0026）
		String processIntNo = request.getParameter("processIntNo");//null
		String processIntId = request.getParameter("processIntId");//流程实例ID
		String relationshipId = request.getParameter("relationshipId");//冲红记录关联的核销记录ID
		String fundDecomNo = request.getParameter("fundDecomNo");//分解单编号
		String fundDecomUsrId = request.getParameter("fundDecomUsrId");//分解人编号
		String fundDecomUsrNm = request.getParameter("fundDecomUsrNm");//分解人名称
		String fundDecomTm = request.getParameter("fundDecomTm");//分解操作时间
		String fundRedRem = request.getParameter("fundRedRem");//冲红原因
		String version = request.getParameter("version");//版本

		//验证参数并赋值
		CapFundVfDtlVO entity = new CapFundVfDtlVO();
 		//entity.setFundId(fundId);//资金ID
 		//entity.setVfWayCd(vfWayCd);//核销方式CAP0003：0—手动核销 1—自动核销
 		//entity.setVfStsCd(vfStsCd);//核销状态集合 CAP0004：0.未核销1.核销中2.已核销3.已作废4.冲红中5.已冲红6.已转出
 		//entity.setPaySchId(paySchId);//支付表ID
 		//entity.setPaySchNo(paySchNo);//支付表号
 		//entity.setPayDetailId(payDetailId);//支付明细表ID
 		//entity.setPayPd(payPd);//支付表期次
 		//entity.setFeeTypCd(feeTypCd);//费用类型代码（PRJ0026）
 		//entity.setProcessIntNo(processIntNo);//null
 		//entity.setProcessIntId(processIntId);//流程实例ID
 		//entity.setRelationshipId(relationshipId);//冲红记录关联的核销记录ID
 		//entity.setFundDecomNo(fundDecomNo);//分解单编号
 		//entity.setFundDecomUsrId(fundDecomUsrId);//分解人编号
 		//entity.setFundDecomUsrNm(fundDecomUsrNm);//分解人名称
 		//entity.setFundDecomTm(fundDecomTm);//分解操作时间
 		//entity.setFundRedRem(fundRedRem);//冲红原因
 		//entity.setVersion(version);//版本
	
//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

		Date tm=new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(tm);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		}else{
			entity.setCrtTm(tm);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			//entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
		}
		
		return entity;
	}
}

